package com.wus.gateway.util;

import cn.hutool.json.JSONUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

/**
 * @Description: jwt工具类
 * @Author: wus
 * @Date: 2024/12/17 11:45
 */
@Component
public class JwtUtils {

    // 设置有效期30min
    private static final long JWT_EXPIRE = 30 * 60 * 1000L;

    // 生成密钥
    @Value("${jwt.secret:ZWRmaGp2cmZmZjFpOWQwV01HWUs9PS0tMCVAODc4aGZ3MTIhJUAqW11zczRzM3NzMTBzczdzcyoqKioqQmJRS3V1S0tkZGRzMDhzLiwub29vb29vbzExMTExMW5ubjhubiwscw==}")
    private String secret;

    /**
     * 用jwt创建token
     * @param data
     * @return
     */
    public String createToken(Object data){
        // 当前时间
        long currentTime = System.currentTimeMillis();
        // 过期时间
        long expireTime = currentTime + JWT_EXPIRE;
        // 构建jwt
        JwtBuilder builder= Jwts.builder()
                .setId(UUID.randomUUID()+"")
                .setSubject(JSONUtil.toJsonStr(data))
                .setIssuer("system")
                .setIssuedAt(new Date(currentTime))
                .signWith(SignatureAlgorithm.HS512, secret)
                // 永不过期，最后以redis cache判断的为准
                //.setExpiration(new Date(expireTime))
                ;
        return builder.compact();
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public Claims parseToken(String token){
        Claims body=Jwts.parser()
                .setSigningKey(secret)
                .build()
                .parseClaimsJws(token)
                .getBody();
        return body;
    }

    /**
     * 解析token，返回json格式对象
     * @param token
     * @param tClass
     * @param <T>
     * @return
     */
    public <T> T parseToken(String token, Class<T> tClass){
        Claims body=Jwts.parser()
                .setSigningKey(secret)
                .build()
                .parseClaimsJws(token)
                .getBody();
        return JSONUtil.toBean(body.getSubject(), tClass);
    }
}
